/**
 * Created by zhanglihe on 15/11/10.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'ckeditor'
], function ($, common, ready, template, Model, dialog, ckeditor) {

    var id = getUrlPath(4);

    var index = function () {
        this.init();
    };
    var _goods_this;
    index.prototype = {
        init: function () {
            var _this = this;
            _this.spec_key = [];//存储当前所有的规格参数
            //商品属性
            $.ajax({
                url: _global.url.api + 'goods_attrs',
                data: {limit: 1000},
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        var goods_attrs = {};
                        $.each(res.data, function () {
                            goods_attrs[this.id] = this;
                        });
                        _this.set('goods_attrs', goods_attrs);
                    }
                }
            });
            //分类
            $.ajax({
                url: _global.url.api + 'site_categorys',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('category', res.data);
                    }
                }
            });
            //运费模板
            $.ajax({
                url: _global.url.api + 'shipping',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('shipping', res.data);
                    }
                }
            });
            //行邮税类目
            if (_global.site_info.is_oversea == 1) {
                $.ajax({
                    url: _global.url.api + 'oversea_catalogs',
                    type: 'get',
                    async: false,
                    success: function (res) {
                        if (res.code == 0) {
                            _this.set('catalogs', res.data);
                        }
                    }
                });
            }
            this.goodsSkuInit(); //初始化sku
            this.albumInit();
            this.fetch();
            this.event();
        },
        formData: {},
        fetch: function () {
            var _this = this;
            //console.log(111);
            //$('input[name="sku_stock"]').attr('readonly', 'readonly');
            //$('#main-view').html(template('add-tpl', {shipping: this.shipping}));
            //隐藏包邮产品的库存
            //if ($('.is-free-shipping').attr('checked') == true') {
            //   $('.weight').hide();
            //};

            this.model = new Model({
                url: _global.url.api + 'goods/' + id,
                sync: function () {
                    //遍历catalog,指定selected项
                    var model = this;
                    var catalogChild = {};
                    var tax_info = {};
                    var is_tax_info = false;
                    if (typeof _this.catalogs !== 'undefined') {
                        $.each(_this.catalogs, function () {
                            if (typeof this.child[model.data.catalog_id] !== 'undefined') {
                                this.selected = 1;
                                this.child[model.data.catalog_id].selected = 1;
                                catalogChild = this.child;
                                //console.log(this.child[model.data.catalog_id]);

                                tax_info = {
                                    'import_tax': this.child[model.data.catalog_id].import_tax,
                                    'consumption_tax': this.child[model.data.catalog_id].consumption_tax,
                                    'value_added_tax': this.child[model.data.catalog_id].value_added_tax
                                };
                                is_tax_info = true;
                            }
                        });
                    }
                    $('#main-view').html(template('add-tpl', {
                        shipping: _this.shipping, catalogs: _this.catalogs,
                        catalogChild: catalogChild, goods: this.data, is_oversea: _global.site_info.is_oversea
                    }));
                    _goods_this = this.data;
                    if (is_tax_info) {
                        $('[name=import_tax]').val(tax_info.import_tax);
                        $('[name=consumption_tax]').val(tax_info.consumption_tax);
                        $('[name=value_added_tax]').val(tax_info.value_added_tax);
                        $('.tax').show();
                    }
                    this.renderCate();
                    this.renderImage();
                    this.renderGoodsAttr();
                    this.renderGoodsSku();
                    this.renderSpecification();
                },
                //有填写规格则输出，没有填写过则输出该分类被分配的所有规格
                renderSpecification: function () {
                    if (this.data.specification == null) {
                        return true;
                    }
                    $.each(this.data.specification, function () {
                        this.value = this.value ? this.value : '';

                        var spec = new Array();
                        spec['name'] = this.specification_id;
                        spec['required'] = this.is_required;
                        spec['title'] = this.title;
                        _this.spec_key.push(spec);

                        var htm;
                        if (this.is_required == '1') {
                            htm = '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + '<span class="color_red">*</span>:<input type="text" name="' + this.specification_id + '" class="form-control" value="' + this.value + '"></label><br>';
                        } else {
                            htm = '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + ':<input type="text" name="' + this.specification_id + '" class="form-control" value="' + this.value + '"></label><br>';
                        }
                        $('#myspecification').append(htm);
                    })
                },
                //输出分类
                renderCate: function () {
                    _this.model.data.cate_ids = [];
                    $.each(this.data.category, function () {
                        _this.model.data.cate_ids.push(this.id);
                        _this.cate.add(this.id, this.name);
                    });
                },
                //输出图册
                renderImage: function () {
                    var model = this;
                    $.each(this.data.album, function () {
                        var el = $(template('img-tpl', this));
                        //if (model.data.image == this.fileUrl) {
                        //    el.addClass('default');
                        //}
                        _this.album.add(el);
                    });

                    //处理图片的左右点击替换事件的move函数
                    function move() {
                        $(".album-list li").find('a.up').show();
                        $(".album-list li").find("a.down").show();
                        $(".album-list li:eq(0)").find("a.up").hide();
                        $(".album-list li:last").find("a.down").hide();

                    }

                    //处理图片的左右点击替换事件
                    move();
                    $(".up").off().on("click", function (e) {
                        e.stopPropagation();
                        $(this).parents("li").insertBefore($(this).parents("li").prev());
                        move();
                        return false;
                    });
                    $(".down").off().on("click", function (e) {
                        e.stopPropagation();
                        $(this).parents("li").insertAfter($(this).parents("li").next());
                        move();
                        return false;
                    });
                    $("#album-view li").mouseover(function () {
                        $(".showmove").show();
                    });
                    $("#album-view li").mouseout(function () {
                        $(".showmove").hide();
                    });

                },
                //输出sku
                renderGoodsAttr: function () {
                    $.each(this.data.goods_attr, function () {
                        $('#sku-attrs').append('<label class="label label-info">' + this.name + '</label> ');
                    });
                    _this.attrs = this.data.goods_attr;
                },
                //输出goods_sku
                renderGoodsSku: function () {
                    var model = this;
                    $.each(this.data.goods_sku, function () {
                        _this.goodsSku.add(this, model.data.goods_attr);
                    });
                }
            });

            this.model.fetch();
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function () {
            var _this = this;

            $('body').on('click', '[name="_is_free_shipping_"]', function() {
                var isFree = $(this).val();

                $('#shipping_template').empty();
                $('#shipping_template').append('<option value="">--请选择--</option>');
                $('#shipping_template option').each(function(index, value) {
                    var optionSid = $(value).attr('s-id');
                    for (var i = 0; i < _this.shipping.length; i++) {
                        var f = _this.shipping[i];
                        var isSelected = '';
                        if (f.id == _this.model.data.shipping_template) {
                            isSelected = 'selected="selected"';
                        }
                        if (isFree == 1) {
                            if (!f.site_id || f.is_free == 1) {
                                $('#shipping_template').append('<option '+isSelected+' s-id="'+ f.site_id+'" value="'+f.id+'">'+f.name+'</option>');
                            }
                        } else {
                            if (f.site_id > 0 && f.is_free == 0) {
                                $('#shipping_template').append('<option '+isSelected+' s-id="'+ f.site_id+'" value="'+f.id+'">'+f.name+'</option>');
                            }
                        }
                    }
                });
            });


            $('input,select,textarea').on('change', function (e) {
                _this.change(e);
            });

            //是否包邮与商品重量联动
            $('.is-free-shipping').on('click', function () {
                $('.weight').hide();
            });

            $('.not-free-shipping').on('click', function () {
                $('.weight').show();
            });
            $('[name=_byself]').on('click', function () {
                var valTmp = $(this).val();
                if(valTmp==1){
                    $('.free-shipping-div').hide();
                }else{
                    $('.free-shipping-div').show();
                }
            });
            $("input[name='weight']").blur(function () {
                var weight = $(this).val();
                //alert(weight);
                if (weight < 0) {
                    $('.weight-info').html('重量必须大于0')
                    $(this).focus();
                } else if (weight == 0) {
                    $('.weight-info').html('重量必须大于0')
                    $(this).focus();
                } else {
                    $('.weight-info').html('');
                }
            });

            //进口税
            $('[name="is_free_tax"]').on('click', function () {
                if ($(this).is(':checked')) {
                    $('#tax_money').show();
                    $('.sku_is_include_tax').show();
                } else {
                    $('#tax_money').hide();
                    $('.sku_is_include_tax').hide();
                }
            });

            //进口税
            /*$('[name="sku_is_free_tax"]').on('click', function () {
             if ($('[name="is_free_tax"]').is(':checked')) {
             if($(this).is(':checked')) {
             $('.sku_is_include_tax').show();
             } else {
             $('.sku_is_include_tax').hide();
             }
             } else {
             alert('请您先勾选包税！');
             return false;
             }
             });*/

            //保存事件
            $('.btn-save').on('click', function (e) {
                e.preventDefault();
                var group_price = $("#group_price").val();
                var group_discount = $('#group_discount').val();
                var data_type = $(this).attr('data-type');

                if (group_price < 0 && group_discount == 0) {
                    var cate_ids = new Array();
                    $('#cate-name').children().each(function () {
                        cate_ids.push($(this).attr('id'));
                    });
                    console.info('=------', cate_ids);
                    $.ajax({
                        url: _global.url.api + 'not_group_two_cate',
                        data: {cate_ids: cate_ids},
                        type: 'put',
                        success: function (res) {
                            if (res == 0) {
                                dialog({
                                    title: '请设置2人拼团价',
                                    content: template('group-two-tpl'),
                                    width: 500,
                                    ok: function () {
                                        var data = {};
                                        data.group_price = $('#group-price-tpl').val();
                                        data.group_discount = $('#group-discount-tpl').val();
                                        data.goods_id = id;
                                        console.log(data);
                                        if (new Model({
                                                url: _global.url.api + 'group_two',
                                                data: data
                                            }).put()) {
                                        }
                                        var group_price = parseFloat(data.group_price);
                                        $("#group_price").val(group_price.toFixed(2));
                                    }, cancel: function () {
                                    }
                                }).show();
                            } else {

                                _this.formData.act = 'edit';
                                //分类
                                var cate_ids = _this.cate.get();
                                _this.formData.cate_ids = cate_ids;

                                //相册
                                var album_length = $('[name="album"]').length;
                                var album = [];
                                for (var i = 0; i < album_length; i++) {
                                    album[i] = $('[name="album"]').eq(i).val();
                                }
                                //console.log(album);
                                _this.formData.album = album;
                                //商品详情
                                _this.formData.details = $('[name="details"]').val();
                                _this.formData.intro = $('[name="intro"]').val();
                                _this.formData.rebate = $('[name="rebate"]').val();
                                _this.formData.stock = $('[name="stock"]').val();
                                _this.formData.old_stock = $('[name="old_stock"]').val();
                                //属性
                                _this.formData.goods_attr_ids = _this.getAttrId();
                                _this.formData.market_price = $("#market_price").val();
                                _this.formData.price = $("#price").val();
                                _this.formData.goods_unicoin = $("[name='goods_unicoin']").val();
                                _this.formData.maidian = $("[name='maidian']").val();
                                _this.formData.group_price = $("#group_price").val();
                                _this.formData.act = 'edit';
                                if (Number(_this.formData.market_price) < Number(_this.formData.price)) {
                                    Alert({msg: '市场价要大于等于121价', type: 'error'});
                                    $("#market_price").val("");
                                    return false;
                                }
                                //goods_sku
                                if (!_this.goodsSku.validation()) {
                                    return false;
                                }
                                //console.log(_this.goodsSku);
                                var old_sku_stock = new Array();
                                $("input[name='old_sku_stock']").each(function () {
                                    old_sku_stock.push($(this).val());
                                });
                                _this.formData.old_sku_stock = old_sku_stock.join(',');
                                //是否跨境购
                                _this.formData.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                                //是否包税
                                _this.formData.is_free_tax = $('input[name="is_free_tax"]').is(':checked') ? 1 : 0;
                                _this.formData.tax_money = $('[name="tax_money"]').val();
                                //是否单品包邮
                                _this.formData._is_free_shipping_ = $('input[name="_is_free_shipping_"]:checked').val();
                                _this.formData._baoming = $('input[name="_baoming"]:checked').val();
                                _this.formData._byself = $('input[name="_byself"]:checked').val();
                                //商品规格参数
                                _this.formData.video = $("#video").val();
                                _this.formData.position = $("input[name='video']:checked").val();
                                var spec = _this.getSpecification();

                                var maps = new Object();
                                for (var i = 0; i < spec.length; i++) {
                                    var lab = $('#spec' + spec[i]['name']).attr('id');

                                    if (typeof(lab) === 'undefined') {
                                        continue;
                                    }
                                    if (typeof(spec[i]['value']) === 'undefined' || spec[i]['value'].length == '0') {
                                        if (spec[i]['required'] == '1') {
                                            Alert({msg: spec[i]['title'] + '为必填项', type: 'error'});
                                            return false;
                                        } else {
                                            continue;
                                        }
                                    }
                                    maps[spec[i]['name']] = spec[i]['value'];
                                }
                                _this.formData.specification = maps;

                                console.log(_this.formData);
                                new Model({
                                    url: _global.url.api + 'goods/' + id,
                                    data: _this.formData,
                                    valid_config: {},
                                    success: function () {
                                        Alert({'msg': '修改成功'});console.log(data_type);
                                        if (data_type == 2) _this.privew_goods(id);
                                    }
                                }).put();
                            }
                        }
                    });
                } else {
                    _this.formData.act = 'edit';
                    //分类
                    var cate_ids = _this.cate.get();
                    console.info(cate_ids);
                    _this.formData.cate_ids = cate_ids;
                    //if (cate_ids.sort().toString() !== _this.model.data.cate_ids.sort().toString()) {
                    //    _this.formData.cate_ids = cate_ids;
                    //}
                    //相册
                    var album_length = $('[name="album"]').length;
                    var album = [];
                    for (var i = 0; i < album_length; i++) {
                        album[i] = $('[name="album"]').eq(i).val();
                    }
                    //console.log(album);
                    _this.formData.album = album;
                    //商品详情
                    _this.formData.details = $('[name="details"]').val();
                    _this.formData.intro = $('[name="intro"]').val();
                    _this.formData.rebate = $('[name="rebate"]').val();
                    _this.formData.stock = $('[name="stock"]').val();
                    _this.formData.old_stock = $('[name="old_stock"]').val();
                    //属性
                    _this.formData.goods_attr_ids = _this.getAttrId();
                    _this.formData.market_price = $("#market_price").val();
                    _this.formData.price = $("#price").val();
                    _this.formData.goods_unicoin = $("[name='goods_unicoin']").val();
                    _this.formData.maidian = $("[name='maidian']").val();
                    _this.formData.group_price = $("#group_price").val();
                    _this.formData.act = 'edit';
                    if (Number(_this.formData.market_price) < Number(_this.formData.price)) {
                        Alert({msg: '市场价要大于等于121价', type: 'error'});
                        $("#market_price").val("");
                        return false;
                    }
                    //goods_sku
                    if (!_this.goodsSku.validation()) {
                        Alert({"msg":"商品属性验证失败", "type":"error"});
                        return false;
                    }
                    //console.log(_this.goodsSku);
                    var old_sku_stock = new Array();
                    $("input[name='old_sku_stock']").each(function () {
                        old_sku_stock.push($(this).val());
                    });
                    _this.formData.old_sku_stock = old_sku_stock.join(',');
                    //是否跨境购
                    _this.formData.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                    //是否包税
                    _this.formData.is_free_tax = $('input[name="is_free_tax"]').is(':checked') ? 1 : 0;
                    _this.formData.tax_money = $('[name="tax_money"]').val();
                    //是否单品包邮
                    _this.formData._is_free_shipping_ = $('input[name="_is_free_shipping_"]:checked').val();
                    _this.formData._baoming = $('input[name="_baoming"]:checked').val();
                    _this.formData._byself = $('input[name="_byself"]:checked').val();
                    //商品规格参数
                    _this.formData.video = $("#video").val();
                    _this.formData.position = $("input[name='video']:checked").val();
                    var spec = _this.getSpecification();

                    console.log('sku-save-before--------------', _this.formData);


                    var maps = new Object();
                    for (var i = 0; i < spec.length; i++) {
                        var lab = $('#spec' + spec[i]['name']).attr('id');

                        if (typeof(lab) === 'undefined') {
                            continue;
                        }
                        if (typeof(spec[i]['value']) === 'undefined' || spec[i]['value'].length == '0') {
                            if (spec[i]['required'] == '1') {
                                Alert({msg: spec[i]['title'] + '为必填项', type: 'error'});
                                return false;
                            } else {
                                continue;
                            }
                        }
                        maps[spec[i]['name']] = spec[i]['value'];
                    }
                    _this.formData.specification = maps;


                    console.log('sku-save-after--------------', _this.formData);
                    new Model({
                        url: _global.url.api + 'goods/' + id,
                        data: _this.formData,
                        valid_config: {},
                        success: function () {
                            Alert({'msg': '修改成功'});console.log(data_type);
                            if (data_type == 2) _this.privew_goods(id);
                            //window.location.reload(true);
                        }
                    }).put();
                }

            });
            $("#market_price").blur(function (e) {
                e.preventDefault();
                var price = $.trim($("#price").val());
                if (Number($.trim($(this).val())) < Number(price) && $.trim($(this).val()) != '') {
                    Alert({msg: '市场价要大于等于121价', type: 'error'});
                    $("#market_price").val("");
                    return false;
                }
            });
            //行邮税
            $('[name="is_oversea"]').on('click', function () {
                if ($(this).is(':checked')) {
                    $('#form-catalog').slideDown();
                    $('.tax').show();
                } else {
                    $('#form-catalog').slideUp();
                    $('.tax').hide();
                }
            });
            $('[name="is_site_config_rebate"]').on('click', function () {
                if ($(this).is(':checked')) {
                    $('.goods-rebate').hide();
                    $('[name="rebate"]').val(-1);
                } else {
                    $('.goods-rebate').show();
                    $('[name="rebate"]').val(20);
                }
            });
            $('select[name="catalog_pid"]').on('change', function () {
                var id = $(this).val();
                if (typeof _this.catalogs[id].child !== 'undefined') {
                    $('select[name="catalog_id"]').html('');
                    $('select[name="catalog_id"]').append('<option value="">请选择</option>');
                    $.each(_this.catalogs[id].child, function () {
                        $('select[name="catalog_id"]').append('<option value="' + this.id + '">' + this.name + '</option>');
                    });
                }
                $('.tax').hide();
            });
            $('select[name="catalog_id"]').on('change', function () {
                var pid = $('[name = "catalog_pid"]').val();
                var id = $(this).val();
                if (typeof _this.catalogs[pid].child !== 'undefined') {
                    var child = _this.catalogs[pid].child;
                    //console.log(child);
                    if (typeof child[id] !== 'undefined') {
                        tax_info = {
                            'import_tax': child[id].import_tax,
                            'consumption_tax': child[id].consumption_tax,
                            'value_added_tax': child[id].value_added_tax
                        };
                    }
                    if (tax_info) {
                        $('[name=import_tax]').val(tax_info.import_tax);
                        $('[name=consumption_tax]').val(tax_info.consumption_tax);
                        $('[name=value_added_tax]').val(tax_info.value_added_tax);
                        $('.tax').show();
                    }
                }
            });

            //选择分类
            $('#btn-cate').on('click', function (e) {
                e.preventDefault();
                _this.selectCate(e);
            });

            $('body').on('click', '.sku-image', function(e) {
                e.preventDefault();
                var that = $(this);
                var uploadDialog = dialog({
                    content: template('upload-tpl2', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame2")[0].contentWindow.image.get();
                        var $input = that.find('input');
                        that.find('img').attr('src', img.fileUrl);
                        $input.val(img.id);
                        _this.change($input);
                        $input.trigger('change');
                        //处理图片的左右点击替换事件的move函数
                        function move() {
                            $(".album-list li").find('a.up').show();
                            $(".album-list li").find("a.down").show();
                            $(".album-list li:eq(0)").find("a.up").hide();
                            $(".album-list li:last").find("a.down").hide();

                        }

                        //// 处理图片的左右点击替换事件
                        //move();
                        //$(".up").off().on("click", function (e) {
                        //    e.stopPropagation();
                        //    $(this).parents("li").insertBefore($(this).parents("li").prev());
                        //    move();
                        //    return false;
                        //});
                        //$(".down").off().on("click", function (e) {
                        //    e.stopPropagation();
                        //    $(this).parents("li").insertAfter($(this).parents("li").next());
                        //    move();
                        //    return false;
                        //});
                        //$("#album-view li").mouseover(function () {
                        //    $(".showmove").show();
                        //});
                        //$("#album-view li").mouseout(function () {
                        //    $(".showmove").hide();
                        //});
                    }, cancel: function () {
                    }
                });
                uploadDialog.show();

            });

            //上传图片
            $('body').on('click', '#btn-upload', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);


                        //处理图片的左右点击替换事件的move函数
                        function move() {
                            $(".album-list li").find('a.up').show();
                            $(".album-list li").find("a.down").show();
                            $(".album-list li:eq(0)").find("a.up").hide();
                            $(".album-list li:last").find("a.down").hide();

                        }

                        //处理图片的左右点击替换事件
                        move();
                        $(".up").off().on("click", function (e) {
                            e.stopPropagation();
                            $(this).parents("li").insertBefore($(this).parents("li").prev());
                            move();
                            return false;
                        });
                        $(".down").off().on("click", function (e) {
                            e.stopPropagation();
                            $(this).parents("li").insertAfter($(this).parents("li").next());
                            move();
                            return false;
                        });
                        $("#album-view li").mouseover(function () {
                            $(".showmove").show();
                        });
                        $("#album-view li").mouseout(function () {
                            $(".showmove").hide();
                        });
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });

            //上传视频
            $('body').on('click', '#btn-upload-video', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-video-tpl', {}),
                    width: 550,
                    ok: function () {
                        var video = $("#upload-frame1")[0].contentWindow.video.get();
                        _this.videoPreview(video);
                        console.log(video);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });

            //选择sku
            $('#btn-select-sku').on('click', function (e) {
                _this.selectSku(e);
            });
            $("body").on("click", '.video-remove', function (e) {
                e.preventDefault();
                $(this).parent('li').remove();
            });
            //添加sku
            $('#btn-add-sku').on('click', function (e) {
                e.preventDefault();
                if (typeof _this.attrs === 'undefined' || _this.attrs.length == 0) {
                    Alert({msg: '请先选择属性', type: 'error'});
                    return false;
                }
                _this.goodsSku.add({}, _this.attrs);
                //$('#goods-sku-view li').each(function () {
                //    $('input[name="sku_stock"]').attr('readonly', 'readonly');
                //});
                //$('#goods-sku-view li label:eq(3) input').attr('readonly', 'readonly');
                //点击加载
                $('#goods-sku-view li input[name="sku_stock"]').removeAttr('readonly');

                if ($('[name="is_free_tax"]').is(':checked')) {
                    $('.sku_is_include_tax').show();
                }


            });

            //编辑器
            $('[name="details"]').ckeditor();
            $('#intro').ckeditor({toolbar: []});
        },

        /**
         * edit by hp
         * @param uri
         */
        callback: function (uri) {
            if (uri) {
                window.location.href = uri;
            }
        },
        privew_goods: function (goods_id) {
            this.data = {};
            var _this = this;
            var html = template('preview_goods-tpl', {goods_id: goods_id});
            _this.dialog = dialog({
                title: '预览商品',
                content: html,
                width: 320,
                height: 568,
                ok: function () {

                }, cancel: function () {
                }
            });
            _this.dialog.show();
        },

        //验证市场价小于121价，暂时先放在这里吧
        validation: function (name) {
            console.info(name);
            if (name == 'market_price') {
                var price = typeof this.formData.price === 'undefined' ? this.model.get_data('price') : this.formData.price;
                var dom = $('[name="' + name + '"]');
                if (this.formData['market_price'] == '' || this.formData['market_price'] < price) {
                    if (dom.parent().hasClass('has-error')) {
                        return;
                    }
                    dom.parent().addClass('has-error').append('<span class="label label-warning error-msg">' + dom.attr('data-error-msg') + '</span>');
                } else {
                    dom.parent().removeClass('has-error').find('.error-msg').remove();
                }
            }
        },
        change: function (e) {
            this.formData[$(e.target).attr('name')] = $(e.target).val();
            this.validation($(e.target).attr('name'));
        },

        getChild: function (id) {
            if (typeof id === 'object') id = id[0];
            var child = [];
            for (var n in this.category) {
                if (id == this.category[n].id) {
                    child = this.category[n].child;
                    break;
                }
            }
            return child;
        },
        imgPreview: function (img) {
            var _this = this;
            $.each(img, function (n, v) {
                if (typeof v.id !== 'undefined') {
                    _this.album.add($(template('img-tpl', v)));
                }
            });
        }, videoPreview: function (video) {
            var _this = this;
            console.log(video.id);
            if (typeof video.id !== 'undefined') {
                $('#video-view').html(template('video-tpl', video));
            }
        },

        //选择分类
        selectCate: function (e) {
            var _this = this;
            if (typeof _this.model.data.cate_ids == 'undefined') {
                _this.model.data.cate_ids = [];
            }
            //一级分类
            _this.cate_form = $(template('cate-tpl', {}));
            $.each(_this.category, function (n, v) {
                _this.cate_form.find('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
            });
            //显示二级分类，并联动
            //bind change event
            _this.cate_form.find('[name="cate"]').on('change', function () {
                _this.cate_form.find('[name="child-cate"]').html('');
                var child = _this.getChild($(this).val());
                $.each(child, function (n, v) {
                    _this.cate_form.find('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                });
            });
            //显示弹框
            _this.dialog = dialog({
                content: _this.cate_form,
                width: 400,
                ok: function () {
                    $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function (n, option) {
                        if (_this.model.data.cate_ids.indexOf(option.value) >= 0) {
                            return false;
                        }
                        _this.cate.add(option.value, option.text);

                        //根据分类输出规格
                        $.ajax({
                            url: _global.url.api + 'get_specification',
                            data: {id: option.value, isGroup: false},
                            type: 'get',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var item = res.data.mySpec;
                                    //var spec_key = [];
                                    //$('#myspecification').children().remove();
                                    $.each(item, function () {
                                        var exist = document.getElementById('spec' + this.specification_id);
                                        if (exist) {
                                            return true;
                                        }
                                        var spec = new Array();
                                        spec['name'] = this.sid;
                                        spec['required'] = this.is_required;
                                        spec['title'] = this.title;
                                        _this.spec_key.push(spec);
                                        var htm = '';
                                        if (this.is_required == '1') {
                                            htm += '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + '<span class="color_red">*</span>:<input type="text" name="' + this.sid + '" class="form-control" value=""></label><br>';
                                        } else {
                                            htm += '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + ':<input type="text" name="' + this.sid + '" class="form-control" value=""></label><br>';
                                        }
                                        $('#myspecification').append(htm);
                                    });
                                }
                            }
                        });
                    });

                    //处理点击添加分类时不需要两人拼团价的分类
                    var cate_ids = new Array();
                    $('#cate-name').children().each(function () {
                        cate_ids.push($(this).attr('id'));
                    });
                    $.ajax({
                        url: _global.url.api + 'not_group_two_cate',
                        data: {cate_ids: cate_ids},
                        type: 'put',
                        success: function (res) {
                            if (res == 1) {
                                $('.group-two').css({'display': 'none'});
                                //alert($('.group-two').css('display'));
                            } else {
                                $('.group-two').css({'display': 'block'});
                                //alert($('.group-two').css('display'));
                            }
                        }
                    });
                    _this.cate_form.remove();

                }, cancel: function () {
                }
            }).show(e.target);
        },

        //分类集合
        cate: {
            spec: this.spec_key,
            default: {
                deleted: false,
                init: function () {
                    this.event();
                    $('#cate-name').append(this.el);
                },
                event: function () {
                    var _this = this;
                    this.el.on('click', 'a', function (e) {
                        e.preventDefault();
                        _this.el.remove();
                        _this.deleted = true;
                        //var sid = $(this).parents().attr('id');
                        var cids = new Array();
                        $('#cate-name').children().each(function () {
                            cids.push($(this).attr('id'));
                        })
                        //处理删除分类时不需要两人拼团价的分类
                        $.ajax({
                            url: _global.url.api + 'not_group_two_cate',
                            data: {cate_ids: cids},
                            type: 'put',
                            success: function (res) {
                                if (res == 1) {
                                    $('.group-two').css({'display': 'none'});
                                    //alert($('.group-two').css('display'));
                                } else {
                                    $('.group-two').css({'display': 'block'});
                                    //alert($('.group-two').css('display'));
                                }
                            }
                        });
                        $.ajax({
                            url: _global.url.api + 'remove_specification',
                            data: {cid: cids, isGroup: false},
                            type: 'post',
                            dataType: 'json',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var sids = eval(res.data);
                                    var sidsArr = new Array();
                                    for (var i in sids) {
                                        sidsArr[i] = 'spec' + sids[i];
                                    }
                                    var sidsLabel = new Array();
                                    $('#myspecification').children('label').each(function () {
                                        var re = $.inArray($(this).attr('id'), sidsArr);
                                        if (re < 0) {
                                            $(this).next('br').remove();
                                            $(this).remove();
                                        }
                                    })
                                }
                            }
                        });
                    });
                },
                del: function () {

                }
            },
            collection: [],
            add: function (id, name) {
                var el = $('<span class="label label-info mr10" id="' + id + '">' + name +
                ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                this.collection.push($.extend({el: el, id: id, name: name}, this.default));
                this.collection[this.collection.length - 1].init();
            },
            get: function () {
                //var cate_ids = [];
                //$.each(this.collection, function () {
                //    !this.deleted && cate_ids.push(this.id);
                //});
                //return cate_ids;
                //
                var cateIds = [];
                $('#cate-name span').each(function($index, $value) {
                    var i = $(this).attr('id');
                    if (i) {
                        cateIds.push(i);
                    }
                });
                return cateIds;
            }
        },

        //相册dom集合
        albumInit: function () {
            var that = this;
            this.album = {
                default: {
                    init: function () {
                        $('#album-view').append(this.el);
                        this.event();
                    },
                    event: function () {
                        var _this = this;
                        this.el.on('click', '.album-trash', function (e) {
                            _this.del(e);
                        });
                        //.on('click', '.album-default', function (e) {
                        //_this.setDefault(e);
                        //});
                    },
                    del: function (e) {
                        e.preventDefault();
                        this.el.remove();
                        //that.updateAlbum();
                    },
                    setDefault: function (e) {
                        e.preventDefault();
                        this.el.addClass('default').siblings().removeClass('default');
                        //that.updateAlbum();
                    }
                },
                images: [],
                add: function (el) {
                    this.images.push($.extend({el: el}, this.default));
                    this.images[this.images.length - 1].init();
                    //that.updateAlbum();
                },
                get: function () {
                    var images = [];
                    $.each($('[name="album"]'), function () {
                        var image = $(this).val();
                        //主图排前面
                        if ($(this).parent().hasClass('default')) {
                            images.unshift(image);
                        } else {
                            images.push(image);
                        }
                    });
                    return images;
                }
            }
        },
        updateAlbum: function () {
            //this.formData['album'] = this.album.get();
        },

        //选择sku
        selectSku: function (e) {
            e.preventDefault();
            var _this = this;
            var attrIds = JSON.parse(_goods_this.goods_attr_ids);
            console.info(attrIds);
            var selectAttrs = $(e.target).attr('data-selected-attrs');
            if (selectAttrs) {
                var dataSelectedAttrs = JSON.parse($(e.target).attr('data-selected-attrs'));
                if (dataSelectedAttrs && dataSelectedAttrs.length > 0) {
                    attrIds = dataSelectedAttrs;
                }
            }

            var el = $(template('sku-attrs-tpl', {goods_attrs: this.goods_attrs, goods_attr_id:attrIds}));
            dialog({
                content: el,
                width: 400,
                ok: function () {
                    if (el.find('[name="goods_attr"]:checked').length > 2) {
                        Alert({msg: '商品属性最多只能选择两个', type: 'error'});
                        return false
                    }
                    $('#sku-attrs').html(''); //请空容器
                    //重置所有属性checked值
                    $.each(_this.goods_attrs, function () {
                        this.checked = false;
                    });
                    var attrs = [];
                    var selectIds = [];
                    $.each(el.find('[name="goods_attr"]'), function () {
                        if ($(this).is(':checked')) {
                            var id = $(this).val();
                            $('#sku-attrs').append('<label class="label label-info">' + _this.goods_attrs[id].name + '</label> ');
                            _this.goods_attrs[id].checked = true;
                            attrs.push(_this.goods_attrs[id]);
                            selectIds.push(id);
                        }
                    });
                    if (selectIds.length > 0) {
                        selectIds = JSON.stringify(selectIds);
                        $('#btn-select-sku').attr('data-selected-attrs', selectIds);
                    }
                    el.remove();
                    _this.set('attrs', attrs);
                    console.info(111);
                    $('.sku-remove').trigger('click');
                    $('.sku-offline').trigger('click');
                    //_this.goodsSku.reset(attrs);
                }, cancel: function () {
                }
            }).show();
        },

        //获取当前所选属性
        getAttrId: function () {
            var ids = [];
            if (typeof this.attrs === 'undefined') {
                return [];
            }
            $.each(this.attrs, function () {
                ids.push(this.id);
            });
            return ids;
        },
        //规格参数处理
        getSpecification: function () {
            var key = this.spec_key;

            for (var i = 0; i < key.length; i++) {
                var value = $('input[name="' + key[i]['name'] + '"]').val();
                key[i]['value'] = $('input[name="' + key[i]['name'] + '"]').val();
            }
            return key;
        },
        //初始化goodsSku对象
        goodsSkuInit: function () {
            var that = this;
            this.goodsSku = {
                default: {
                    template: 'goods-sku-tpl',
                    deleted: false, //是否已删除
                    init: function () {
                        this.el = $('<li class="list-group-item"></li>');
                        console.log(_goods_this);
                        this.el.html(template(this.template, {attrs: this.attrs, sku: this.data, goods: _goods_this}));
                        $('#goods-sku-view').append(this.el);
                        this.event();
                    },
                    event: function () {
                        var _this = this;
                        this.el.find('.sku-remove').off().on('click', function (e) {
                            e.preventDefault();
                            _this.remove();
                        });
                        this.el.find('.sku-offline').off().on('click', function (e) {
                            e.preventDefault();
                            //dialog({
                            //    content: '永久下架后，此规格将不再显示(保存后生效)，确定要永久下架吗？如果只是暂时缺货，可将库存设置为0',
                            //    ok: function () {
                            //        _this.offline();
                            //    }, cancel: function () {
                            //    }
                            //}).show(e.target);
                            _this.offline();

                        });
                        this.el.find('input,select,input:hidden').off().on('change', function (e) {
                            console.log('监听成功');
                            e.preventDefault();
                            _this.change(e);
                        });

                        //添加2人团购价
                        $('[name="sku_price"]').on('blur', function () {
                            var sku_this = this;
                            $.ajax({
                                url: _global.url.api + 'goods_group_price',
                                data: {
                                    goods_price: $(this).val(),
                                    site_id: _global.site_info.id,
                                    sku_id: $(this).parent().next().find('[name="sku_id"]').val()
                                },
                                type: 'get',
                                dataType: 'json',
                                success: function (res) {
                                    if (res.data > 0) {
                                        $(sku_this).parent().parent().find('[name="sku_group_price"]').val(res.data).change();
                                    } else {
                                        var group_price = ($(sku_this).val() * 0.99).toFixed(2);
                                        $(sku_this).parent().parent().find('[name="sku_group_price"]').val(group_price).change();
                                    }
                                }
                            });
                        });
                    },
                    change: function (e) {
                        console.info(2222);
                        var _this = this;
                        var val = $(e.target).val();
                        if ($(e.target).attr('name') == 'attr_values') {
                            _this.changeAttrValues();
                        } else {
                            var key = $(e.target).attr('name');
                            //移除name前缀attr_(解决干扰price等字段验证)
                            key = key.replace(/sku_/, "");
                            this.data[key] = val;
                        }
                        that.changeSku();
                    },
                    changeAttrValues: function () {
                        var _this = this;
                        _this.data.goods_attr_values = [];
                        var values = _this.el.find('[name="attr_values"]');
                        $.each(_this.attrs, function (n, v) {
                            _this.data.goods_attr_values.push({
                                id: this.id,
                                name: this.name,
                                value: $(values[n]).val()
                            });
                        });
                    },
                    remove: function () {
                        if (that.model.data.status != 0 && typeof(this.data.id) !== 'undefined') {
                            Alert({msg: '非草稿状态，不能删除规格', type: 'error'});
                            return false;
                        }
                        this.el.remove();
                        this.deleted = true;
                        this.data.deleted = 1;
                        that.changeSku();
                    },
                    offline: function () {
                        this.data.status = 2;
                        this.el.html(template(this.template, {attrs: this.attrs, sku: this.data}));
                        //console.log(this.data);
                    }
                },
                collection: [],
                add: function (sku, attrs) {
                    var _coll = $.extend({data: sku, attrs: attrs}, this.default);
                    _coll.init();
                    this.collection.push(_coll);
                    that.changeSku();
                },
                get: function () {
                    var goodsSku = [];
                    console.log('collection:', this.collection)
                    $.each(this.collection, function () {
                        if (!this.deleted || typeof(this.data.id) !== 'undefined') {
                            goodsSku.push(this.data);
                        }
                    });
                    return goodsSku;
                },
                reset: function (attrs) {
                    $.each(this.collection, function () {
                        this.attrs = attrs;
                        this.el.html(template(this.template, {attrs: this.attrs, sku: this.data}));
                        this.changeAttrValues();
                        this.event();
                    });
                    that.changeSku();
                },
                //验证属性填写是否完整
                validation: function () {
                    var _this = this;
                    var valid = true;
                    if (this.collection.length > 0) {
                        for (var i = 0; i < _this.collection.length; i++) {
                            var cl = _this.collection[i];
                            //console.info('cl', cl);
                            //if (i <= _this.collection.length-2) {
                            //    var nextCl = _this.collection[i+1];
                            //    console.info('nextCl', nextCl);
                            //    var currentGroupCount = cl.data.goods_attr_values.length;
                            //    var currentGroupId = '';
                            //    var nextGroupId = '';
                            //    for (var v = 0; v < currentGroupCount; v++) {
                            //        console.info('----', cl.data.goods_attr_values[v].id, nextGroupId + nextCl.data.goods_attr_values[v].id);
                            //        currentGroupId = currentGroupId + cl.data.goods_attr_values[v].id;
                            //        nextGroupId = nextGroupId + nextCl.data.goods_attr_values[v].id;
                            //    }
                            //    console.info(currentGroupId, nextGroupId);
                            //    if (currentGroupId == nextGroupId) Alert({"msg":"相同属性只能有一个SKU", "type":"error"});
                            //}

                            if (cl.deleted == true || cl.data.status == 2) continue;

                            //if (cl.deleted === false) {
                                //sn
                                /*if(!cl.data.sn) {
                                 _this.error('属性编码不能为空');
                                 valid = false;
                                 break;
                                 }*/
                                if (cl.data.price != 0 && !parseInt(cl.data.price) && !parseFloat(cl.data.price)) {
                                    _this.error('属性价格填写不正确');
                                    valid = false;
                                    break;
                                }
                                if (isNaN(parseInt(cl.data.stock)) || parseInt(cl.data.stock) < 0) {
                                    _this.error('属性库存填写不正确');
                                    valid = false;
                                    break;
                                }


                                var attrCl = cl.data.goods_attr_values;
                                if (_this.collection.length > 1) {
                                    for (var t = i+1; t < _this.collection.length; t++) {

                                        var currentCl = _this.collection[t];
                                        if (currentCl.deleted == true || currentCl.data.status == 2) continue;

                                        var nextAttrCl = _this.collection[t].data.goods_attr_values;
                                        var nextRowV = '', rowV = '';
                                        if (attrCl) {
                                            for (var vi = 0; vi < attrCl.length; vi++) {
                                                nextRowV = nextRowV + nextAttrCl[vi].value;
                                                rowV = rowV + attrCl[vi].value;
                                            }
                                            if (rowV == nextRowV) return false;
                                        }
                                    }
                                }
                            }

                        }
                    //}
                    //return false;

                    return valid;
                },
                error: function (msg) {
                    Alert({msg: msg, typ: 'error'});
                }
            }
        },
        changeSku: function () {
            //this.model.set_data('goods_sku', this.goodsSku.get());
            this.formData.goods_sku = this.goodsSku.get();
        }

    };

    new index();

});